package com.bdit.ydcb.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.service.LocationService;
import com.bdit.ydcb.MyApplication;
import com.bdit.ydcb.R;
import com.bdit.ydcb.callback.DialogCallback;
import com.bdit.ydcb.model.ServerResponse;
import com.bdit.ydcb.utils.Constants;
import com.bdit.ydcb.utils.SPUtils;
import com.bdit.ydcb.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.BodyRequest;
import com.lzy.okgo.request.base.Request;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.ImgLoader;
import com.pizidea.imagepicker.UilImgLoader;
import com.pizidea.imagepicker.bean.ImageItem;

import java.io.File;
import java.util.List;

public class WaterUserAddActivity extends Activity implements  View.OnClickListener{
    private static final String TAG = "WaterUserDetailActivity";
    private LinearLayout top_bar_linear_back;
    private TextView top_bar_title;
    private ImageView imageView;
    private EditText current_num;
    private EditText user_no;
    private EditText user_name;
    private EditText meter_no;
    private EditText phone;
    private EditText address;
    private Button commit_button;
    private String imageUrl="";
    private String areaCode="";
    private double lat;
    private double lng;
    private LocationService locationService;
    ImgLoader presenter = new UilImgLoader();
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_water_user_add);
        findView();
        initData();

    }
    private void findView(){
        top_bar_linear_back = (LinearLayout)this.findViewById(R.id.top_bar_linear_back);
        top_bar_linear_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                WaterUserAddActivity.this.finish();
            }
        });
        top_bar_title = (TextView) this.findViewById(R.id.top_bar_title);
        imageView = (ImageView) this.findViewById(R.id.cb_imageview);
        imageView.setOnClickListener(this);
        current_num = (EditText) findViewById(R.id.current_num);
        current_num.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        user_no = (EditText) findViewById(R.id.user_no);
        user_name = (EditText) findViewById(R.id.user_name);
        meter_no = (EditText) findViewById(R.id.meter_no);
        phone = (EditText) findViewById(R.id.phone);
        address = (EditText) findViewById(R.id.address);
        commit_button = (Button) findViewById(R.id.cb_commit);
        commit_button.setOnClickListener(this);

    }
    private void initData(){
        Intent intent = getIntent();
        areaCode = intent.getStringExtra("areaCode");
        address.setText(SPUtils.get(Constants.ADDRESS,"").toString());
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cb_imageview:
                AndroidImagePicker.getInstance().pickSingle(WaterUserAddActivity.this, true, new AndroidImagePicker.OnImagePickCompleteListener() {
                    @Override
                    public void onImagePickComplete(List<ImageItem> items) {
                        if(items != null && items.size() > 0){
                            Log.i(TAG,"=====选择了："+items.get(0).path);
                            imageUrl = items.get(0).path;
                            presenter.onPresentImage(imageView,items.get(0).path,1000);

                        }
                    }
                });
                break;
            case R.id.cb_commit:
                commit_cb();
                break;
        }

    }
    private  void commit_cb(){
        if ("".equals(imageUrl)) {
            Toast.makeText(WaterUserAddActivity.this,"请选择水表图片",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(current_num.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入水表读数",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(user_no.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入户号",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(user_name.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入户名",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(meter_no.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入水表编号",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(phone.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入联系电话",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(address.getText().toString())){
            Toast.makeText(WaterUserAddActivity.this,"请选输入地址",Toast.LENGTH_SHORT).show();
            return;
        }
        BodyRequest bodyRequest= OkGo.<ServerResponse>post(Urls.POST_CB_URL)
                .tag(this)
                .params("areaCode",areaCode)
                .params("currentNum",current_num.getText().toString())
                .params("userNo",user_no.getText().toString())
                .params("meterNo",meter_no.getText().toString())
                .params("phone",phone.getText().toString())
                .params("address",address.getText().toString())
                .params("userName",user_name.getText().toString())
                .params("lat",lat)
                .params("lng",lng);

        if(!"".equals(imageUrl)){
            File file = new File(imageUrl);
            bodyRequest.params("file",file);
        }
       bodyRequest.isMultipart(true).execute(new DialogCallback<ServerResponse>(this) {
            @Override
            public void onStart(Request<ServerResponse, ? extends Request> request) {
                setDialogMessage("提交中...");
                super.onStart(request);
            }

            @Override
            public void onSuccess(Response<ServerResponse> response) {
                ServerResponse result = response.body();
                if(result.success){
                    WaterUserAddActivity.this.finish();
                }else{
                    Toast.makeText(WaterUserAddActivity.this,result.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
    /**
     * 显示请求字符串
     *
     * @param str
     */
    public void logMsg(String str) {
        final String s = str;
        try {
            if (address != null){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        address.post(new Runnable() {
                            @Override
                            public void run() {
                                address.setText(s);
                            }
                        });

                    }
                }).start();
            }
            //LocationResult.setText(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService =((MyApplication)getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }
    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                lat = location.getLatitude();
                lng = location.getLongitude();
                logMsg(location.getCity()+location.getDistrict()+location.getStreet());
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");

                sb.append(location.getTime());

                sb.append("\nlatitude : ");// 纬度
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");// 经度
                sb.append(location.getLongitude());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());
                sb.append("\nDistrict : ");// 区
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");// 街道
                sb.append(location.getStreet());
                sb.append("\naddr : ");// 地址信息
                sb.append(location.getAddrStr());

              Toast.makeText(WaterUserAddActivity.this,sb.toString(),Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    };


}
